package com.own.demo.lwf.encryption.symEncryption;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

/**
 * @version v1.0
 * @Description:
 * 对称加密使用相同的密钥进行加密和解密
 * 常见的对称加密算法有AES、DES和3DES
 * @Author 李文峰
 * @Date 2023/7/22 0022 7:23
 */
public class AESEncryption {
    // 加密
    public static byte[] encrypt(String key, byte[] data) throws Exception {
        SecretKeySpec spec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, spec);
        return cipher.doFinal(data);
    }

    // 解密
    public static byte[] decrypt(String key, byte[] encrypted) throws Exception {
        SecretKeySpec spec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, spec);
        return cipher.doFinal(encrypted);
    }
}
